package com.hczt.fire.server.backend.sys.controller;

import com.hczt.fire.entity.sys.SysRole;
import com.hczt.fire.entity.sys.SysUser;
import com.hczt.fire.framework.jpa.repository.support.PagedQuery;
import com.hczt.fire.server.backend.sys.service.SysRoleService;
import com.hczt.fire.server.backend.sys.service.SysUserService;
import com.hczt.fire.server.common.Constant;
import com.hczt.fire.server.common.annotation.OperationLog;
import com.hczt.fire.server.common.security.FormToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 把今天最好的表现当作明天最新的起点．．～
 * いま 最高の表現 として 明日最新の始発．．～
 * Today the best performance  as tomorrow newest starter!
 *
 * @author marvin.ma
 * @create 2017-10-20 13:41
 * @desc 系统用户管理
 **/
@Controller
@RequestMapping("/sys/user")
public class SysUserController {

    private static final Logger log = LoggerFactory.getLogger(SysUserController.class);

    private static final String BASE_PATH = "admin/sys/";

    @Resource
    private  SysUserService userService;

    @Resource
    private SysRoleService sysRoleService;
    /**
     * 分页查询管理员列表
     *
     * @param pageNumber   当前页码
     * @param username  用户名
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param modelMap
     * @return
     */
    @RequiresPermissions("user:list")
    @GetMapping
    public String list(@RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber,
            String username, String startTime, String endTime, ModelMap modelMap) throws Exception {
        try {
            log.debug("分页查询管理员列表参数! pageNumber = {}, pageSize = {}, username = {}, startTime = {}, endTime = {}", pageNumber, Constant.PAGE_SIZE, username, startTime, endTime);
            PagedQuery<SysUser> pageInfo = userService.findPage(pageNumber, Constant.PAGE_SIZE, username, startTime, endTime);
            log.info("分页查询管理员列表结果！ pageInfo = {}", pageInfo);
            modelMap.put("pageInfo", pageInfo);
            modelMap.put("username", username);
            modelMap.put("startTime", startTime);
            modelMap.put("endTime", endTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return BASE_PATH + "user-list";
    }

    /**
     * 检验用户名是否存在
     * @param username
     * @return
     */
    @ResponseBody
    @GetMapping(value = "/isExist")
    public Boolean isExist(Long id, String username) throws Exception {
        boolean flag = true;
        log.debug("检验用户名是否存在参数! id= {}, username= {}", id, username);
        SysUser record = userService.findByUserName(username);
        if (null != record && !record.getId().equals(id)) {
            flag = false;
        }
        log.info("检验用户名是否存在结果! flag = {}", flag);
        return flag;
    }

    /**
     * 跳转到管理员添加页面
     * @return
     */
    @FormToken(save = true)
    @RequiresPermissions("user:create")
    @GetMapping(value = "/add")
    public String add(ModelMap modelMap){
        List<SysRole> roleList = sysRoleService.findAll();
        modelMap.put("roleList", roleList);
        log.info("跳转到管理员添加页面!");
        return BASE_PATH + "user-add";
    }

    /**
     * 添加管理员
     * @param user
     * @param roleId  角色ID
     * @return
     */
    @FormToken(remove = true)
    @OperationLog(value = "添加管理员")
    @RequiresPermissions("user:create")
    @ResponseBody
    @PostMapping(value = "/add")
    public ModelMap saveUser(SysUser user, Long roleId) throws Exception {
        ModelMap messagesMap = new ModelMap();

        log.debug("添加管理员参数! user = {}", user);
        Boolean flag = userService.saveUserAndUserRole(user, roleId);
        if(flag){
            log.info("添加管理员成功! userId = {}", user.getId());
            messagesMap.put("status", 200);
            messagesMap.put("message", "添加成功!");
            return messagesMap;
        }
        log.info("添加管理员失败, 但没有抛出异常! userId = {}", user.getId());
        messagesMap.put("status", 400);
        messagesMap.put("message", "添加失败!");
        return messagesMap;
    }
}
